package uk.ac.cam.djjb2.mygame;

import java.io.IOException;
import java.net.InetAddress;

import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.SpriteSheet;

public class MyGame extends BasicGame {
	TileMap map;
	TileSet tileSet;
	SpriteSheet mapSheet;
	ServerNetManager netManager;
	ClientNetManager clientNetManager;
	ReplicaManager replicaManager;
	ClientReplicaManager clientReplicaManager;
	
	public MyGame() {
		super("My Game");
	}
	
	@Override
	public void init(GameContainer container) throws SlickException {
		
		try {
			netManager = new ServerNetManager(4231);
			replicaManager = new ReplicaManager(netManager);
			clientNetManager = new ClientNetManager(InetAddress.getLoopbackAddress(), 4231);
			clientReplicaManager = new ClientReplicaManager(clientNetManager);
		} catch (IOException e) {
		}
		
		try {
			netManager.processMessages();
			clientNetManager.processMessages();
			
			replicaManager.update();
			clientNetManager.processMessages();
			
			TestReplica replica = new TestReplica(replicaManager);

			replicaManager.update();
			Thread.sleep(100);
			clientNetManager.processMessages();
			
			ClientTestReplica clientReplica = 
					clientReplicaManager.getReplica(replica.getId(), ClientTestReplica.class);
			
			replicaManager.update();
			Thread.sleep(100);
			clientNetManager.processMessages();

			clientReplica.getId();
		} catch (IOException | InvalidMessageException | ReplicationException | InterruptedException e) {
			e.printStackTrace();
		}
		
		tileSet = new DefaultTileSet();
		
		mapSheet = new SpriteSheet("map.png", 32, 32);
		map = new TileMap(new Vector2i(64, 64), mapSheet, tileSet);
	
		for (int y = 0; y < 32; y++)
			for (int x = 0; x < 32; x++)
				map.setTileId(
						new Vector2i(x, y),
						1+(int)(Math.random()*4.0)
						);
	}

	@Override
	public void update(GameContainer container, int delta)
			throws SlickException {
	}

	@Override
	public void render(GameContainer container, Graphics g)
			throws SlickException {
		map.render(Vector2i.ZERO, Vector2i.ZERO, map.getSize());
		
		g.drawString(
				Integer.toString(container.getWidth()) + "x"
						+ Integer.toString(container.getHeight()), 10, 25);
	}

	public static void main(String[] args) {
		try {
			AppGameContainer app = new AppGameContainer(new MyGame());
			app.setDisplayMode(800, 600, false);
			app.start();
		} catch (SlickException e) {
			e.printStackTrace();
		}
	}
}